package org.example.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.mapper.AppointmentMapper;
import org.example.pojo.Appointment;
import org.example.pojo.Doctor.OutpatientClinic;
import org.example.service.AdminUserService;
import org.example.service.AppointmentService;
import org.example.service.HospitalService;
import org.example.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Service
public class AppointmentServiceImpl implements AppointmentService {

    @Autowired
    private AppointmentMapper appointmentMapper;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private HospitalService hospitalService;

    @Override
    public void addAppointment(Appointment appointment) {
        appointment.setStatus("待支付");
        appointmentMapper.insertAppointment(appointment);
    }

    @Override
    public void updateAppointmentStatus(Appointment appointment) {
        appointmentMapper.updateAppointmentStatus(appointment.getAppointmentId(), appointment.getStatus());
    }

    @Override
    public void deleteAppointment(Integer appointmentId) {
        appointmentMapper.deleteAppointment(appointmentId);
    }

    @Override
    public List<Appointment> getAppointmentByDay() {
        return appointmentMapper.getAppointmentsByDay();
    }

    @Override
    public List<Appointment> getAppointmentList() {
        return appointmentMapper.getAppointments();
    }
    //根据患者id查询
    @Override
    public List<Appointment> getAppointmentById(Integer patientId) {
        return appointmentMapper.getAppointmentById(patientId);
    }

    private static final Logger logger = LoggerFactory.getLogger(AppointmentServiceImpl.class);

    // 定时任务：每天早上8点统计昨日“已叫号”的预约信息并记录日志

    //测试 10分钟执行一次
    //@Scheduled(fixedRate = 600000)
    @Scheduled(cron = "0 0 8 * * ?") // 每天早上8点执行
    public void logAppointmentStats() {
        // 查询昨日“已叫号”的所有预约信息
        List<Appointment> appointments = appointmentMapper.findYesterdayAppointmentsByStatus();
        appointments.forEach(appointment -> {
            // 通过医生id获取医生姓名
            String doctorName = adminUserService.getDoctorById(appointment.getDoctorId()).getName();
            appointment.setDoctorName(doctorName);
            // 通过科室id获取科室名称
            List<OutpatientClinic> clinics = hospitalService.getAllClinics();
            clinics.forEach(clinic -> {
                if (clinic.getClinicId().equals(appointment.getClinicId())) {
                    appointment.setClinicName(clinic.getClinicName());
                    return; // 找到科室后退出循环
                }
            });
            // 根据patientId获取患者名字
            String patientName = adminUserService.getPatientById(appointment.getPatientId()).getName();
            appointment.setPatientName(patientName);
        });

        // 记录日志
        if (!appointments.isEmpty()) {
            // 遍历并记录每个预约的 JSON 格式日志
            for (Appointment appointment : appointments) {
                Map<String, Object> logData = new HashMap<>();
                logData.put("clinicName", appointment.getClinicName());
                logData.put("patientName", appointment.getPatientName());
                logData.put("doctorName", appointment.getDoctorName());
                logData.put("clinicId", appointment.getClinicId());
                logData.put("appointmentTime", appointment.getAppointmentTime());
                logData.put("patientId", appointment.getPatientId());
                logData.put("doctorId", appointment.getDoctorId());
                logData.put("status", appointment.getStatus());

                // 将日志信息转换为 JSON 格式
                ObjectMapper objectMapper = new ObjectMapper();
                try {
                    String jsonLog = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(logData);
                    logger.info("昨日“已叫号”预约统计信息：\n{}", jsonLog);
                } catch (JsonProcessingException e) {
                    logger.error("日志记录失败", e);
                }
            }
        } else {
            logger.info("昨日无“已叫号”的预约记录。");
        }
    }
    // 定时任务：检查挂号状态
    @Scheduled(fixedRate = 600000) // 每10分钟执行1次
    public void checkAppointmentStatus() {
        // 获取未支付且超过10分钟的挂号记录
        Timestamp tenMinutesAgo = TimeUtils.getTenMinutesAgo();
        List<Appointment> unpaidAppointments = appointmentMapper.findUnpaidAppointments(tenMinutesAgo);
        for (Appointment appointment : unpaidAppointments) {
            String status = "已取消";
            appointmentMapper.updateAppointmentStatus(appointment.getAppointmentId(), status);
        }

        // 检查预约日期已过期的挂号
        List<Appointment> expiredAppointments = appointmentMapper.findExpiredAppointments();
        for (Appointment appointment : expiredAppointments) {
            if (!"已叫号".equals(appointment.getStatus())) {
                String status = "已过期";
                appointmentMapper.updateAppointmentStatusByTime(appointment.getAppointmentTime(), status);
            }
        }
        // 信息超过七天自动删除
        List<Appointment> appointments = appointmentMapper.getSevenAppointments();
        for (Appointment appointment : appointments) {
            appointmentMapper.deleteAppointment(appointment.getAppointmentId());
        }
    }
}